package cn.edu.swu.io_2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ImageManager {

    private Map<String, String> imageMap = new HashMap<>();

    public void downloadImage(String url) throws IOException {
        //图片下载，调用FileUtils.saveImage()下载图片，将信息加入集合

        // 保存特定图片到指定文件夹
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        String savePath = "2_java_io\\images\\" + fileName;
        FileUtils.saveImage(url, savePath);

        // 存入集合和日志
        imageMap.put(fileName, savePath);
        FileUtils.appendLog("Downloaded: " + url + " -> " + savePath);
    }

    public void listImages(){
        // 遍历集合，打印已下载图片列表
        if (imageMap.isEmpty()){
            System.out.println("暂无已下载图片！");
            return;
        }
        // 打印表头
        System.out.println("已下载图片，共"+imageMap.size()+"张");
        System.out.println("==============================");
        int index = 1;
        // 打印每个项目
        for (Map.Entry<String,String> entry : imageMap.entrySet()){
            System.out.println(index + "文件名" + entry.getKey());
            System.out.println("保存路径：" + entry.getValue());
            System.out.println("----------------------------");
            index++;
        }
    }

    public void searchImage(String name){
        // 根据名称查找图片路径
        boolean found = false;

        for (Map.Entry<String,String> entry : imageMap.entrySet()){
            // 统一为小写
            if (entry.getKey().toLowerCase().contains(name.toLowerCase())){
                System.out.println("找到图片: " + entry.getKey());
                System.out.println("路径: " + entry.getValue());
                found = true;
            }
        }

        if (!found){
            System.out.println("未找到名为" + name + "的图片");
        }

    }

}
